/**
 * @file lv_chinese_ime.c
 *
 */

/*********************
 *      INCLUDES
 *********************/
#include "../lv_chinese_ime.h"
#include "chinese_ime.h"

#if LV_CHINESE_IME
#include "cJSON.h"

/*********************
 *      DEFINES
 *********************/

/**********************
 *      TYPEDEFS
 **********************/

/**********************
 *  STATIC PROTOTYPES
 **********************/
static void lv_chinese_ime_constructor(lv_obj_t * obj);
static void lv_chinese_ime_def_event_cb(lv_event_t * e);
static void parse_match_dict(lv_obj_t * keyboard);
static void select_font_event_cb(lv_event_t * e);
static void lv_chinese_ime_destruct(void);

/**********************
 *  STATIC VARIABLES
 **********************/
static lv_chinese_ime_pt lv_chinese_ime;

/**********************
 *      MACROS
 **********************/

/**********************
 *   GLOBAL FUNCTIONS
 **********************/

/**
 * Create a keyboard objects
 * @param par pointer to an object, it will be the parent of the new keyboard
 * @return pointer to the created keyboard
 */
lv_obj_t * lv_chinese_ime_create(lv_obj_t * parent)
{
    LV_LOG_INFO("begin");
    lv_obj_t * obj = lv_keyboard_create(parent);

    lv_chinese_ime_constructor(obj);

    lv_obj_add_event_cb(obj, lv_chinese_ime_def_event_cb, LV_EVENT_VALUE_CHANGED, NULL);
    return obj;
}

/**
 * This is the inheritance and customization of "lv_obj_del".
 * @param obj       pointer to an object
 */
void lv_chinese_ime_del(lv_obj_t * obj)
{
    lv_chinese_ime_destruct();
    lv_obj_del(obj);
}

/**
 * Set dict of input method
 * @param obj       pointer to an dict
 */
void lv_chinese_ime_set_dict(const char * dict)
{
    lv_chinese_ime->dict = dict;
}

/**
 * Similar to "lv_obj_set_style_text_font"
 * @param value       pointer to a font
 * @param selector    selector
 */
void lv_chinese_ime_set_text_font(const lv_font_t * value, lv_style_selector_t selector)
{
    lv_obj_set_style_text_font(lv_chinese_ime->font_panel, value, selector);
}

/*=====================
 * Other functions
 *====================*/

/**********************
 *   STATIC FUNCTIONS
 **********************/

/**
 * This is the inheritance and customization of "lv_keyboard_def_event_cb".
 * @param kb pointer to a keyboard
 * @param event the triggering event
 */
static void lv_chinese_ime_def_event_cb(lv_event_t * e)
{
    lv_obj_t * obj = lv_event_get_target(e);
    uint32_t event = lv_event_get_code(e);

    // printf("=== 键盘事件 ===\n");
    // printf("事件类型: %d\n", event);

    if(event == LV_EVENT_VALUE_CHANGED) {
        uint16_t btn_id = lv_btnmatrix_get_selected_btn(obj);
        // printf("按钮ID: %d\n", btn_id);

        if(btn_id == LV_BTNMATRIX_BTN_NONE) return;

        const char * txt = lv_btnmatrix_get_btn_text(obj, btn_id);
        // printf("按钮文本: '%s'\n", txt);

        if(txt == NULL) return;

        // 测试：输入"ni"这个常见拼音
        if(strcmp(txt, "Enter") == 0 || strcmp(txt, LV_SYMBOL_NEW_LINE) == 0) {
            lv_obj_clean(lv_chinese_ime->font_panel);
            lv_chinese_ime->ta_count = 0;
            memset(lv_chinese_ime->input_char, 0, sizeof(lv_chinese_ime->input_char));
        } else if(strcmp(txt, LV_SYMBOL_BACKSPACE) == 0) {
            if(strlen(lv_chinese_ime->input_char) > 0) {
                lv_chinese_ime->input_char[strlen(lv_chinese_ime->input_char) - 1] = '\0';
                parse_match_dict(obj);
                lv_chinese_ime->ta_count--;
            }
        } else if((txt[0] >= 'a' && txt[0] <= 'z') || (txt[0] >= 'A' && txt[0] <= 'Z')) {
            // 转换为小写
            char lower_char[2] = {tolower(txt[0]), '\0'};

            if(strlen(lv_chinese_ime->input_char) < sizeof(lv_chinese_ime->input_char) - 1) {
                strcat(lv_chinese_ime->input_char, lower_char);
                parse_match_dict(obj);
                lv_chinese_ime->ta_count++;
            }
        }
    }
}

/**
 * Triggered when a font is selected.
 * @param kb pointer to a keyboard
 * @param event the triggering event
 */
static void select_font_event_cb(lv_event_t * e)
{
    lv_obj_t * obj = lv_event_get_target(e);

    lv_obj_t * keyboard = (lv_obj_t *)lv_event_get_user_data(e);
    lv_obj_t * ta       = lv_keyboard_get_textarea(keyboard);

    for(int i = 0; i < lv_chinese_ime->ta_count; i++) {
        lv_textarea_del_char(ta);
    }

    lv_textarea_add_text(ta, lv_label_get_text(obj));

    lv_obj_clean(lv_chinese_ime->font_panel);
    lv_chinese_ime->ta_count = 0;
    lv_memset_00(lv_chinese_ime->input_char, sizeof(lv_chinese_ime->input_char));
}

/**
 * Parse and match dict (based on cJson)
 * @param text
 * @param label
 */
static void parse_match_dict(lv_obj_t * kb)
{
    LV_FONT_DECLARE(SourceHanSansCN_Bold_20);
    // 先清空面板
    lv_obj_clean(lv_chinese_ime->font_panel);

    // // 调试：检查面板状态
    // printf("面板指针: %p\n", lv_chinese_ime->font_panel);
    // printf("面板父对象: %p\n", lv_obj_get_parent(lv_chinese_ime->font_panel));
    // printf("面板是否隐藏: %d\n", lv_obj_has_flag(lv_chinese_ime->font_panel, LV_OBJ_FLAG_HIDDEN));

    // // 强制显示面板
    // lv_obj_clear_flag(lv_chinese_ime->font_panel, LV_OBJ_FLAG_HIDDEN);
    lv_obj_move_foreground(lv_chinese_ime->font_panel);

    if(strlen(lv_chinese_ime->input_char) == 0) {
        // 清空时显示提示 - 使用简单文本测试显示
        // lv_obj_t * hint_label = lv_label_create(lv_chinese_ime->font_panel);
        // // lv_label_set_text(hint_label, "请输入拼音...TEST");
        // lv_obj_set_style_bg_opa(hint_label, LV_OPA_COVER, 0);
        // lv_obj_set_style_pad_all(hint_label, 10, 0);
        return;
    }

    // 解析真实输入
    cJSON * cjson_parse_result = cJSON_Parse(lv_chinese_ime->dict);
    if(cjson_parse_result == NULL) {
        printf("字典解析失败!\n");

        lv_obj_t * error_label = lv_label_create(lv_chinese_ime->font_panel);
        lv_label_set_text(error_label, "字典解析失败");
        // lv_obj_set_style_text_color(error_label, lv_color_hex(0xFF0000), 0);
        // lv_obj_set_style_bg_color(error_label, lv_color_hex(0xFFFF00), 0);
        lv_obj_set_style_bg_opa(error_label, LV_OPA_COVER, 0);
        return;
    }

    cJSON * cjson_skill = cJSON_GetObjectItem(cjson_parse_result, lv_chinese_ime->input_char);
    if(cjson_skill == NULL) {
        // printf("未找到匹配项: %s\n", lv_chinese_ime->input_char);

        // lv_obj_t * no_match_label = lv_label_create(lv_chinese_ime->font_panel);
        // lv_label_set_text(no_match_label, "未找到匹配的汉字");
        // lv_obj_set_style_bg_opa(no_match_label, LV_OPA_COVER, 0);
    } else {
        // printf("找到匹配项!\n");
        int skill_array_size = cJSON_GetArraySize(cjson_skill);
        // printf("匹配数量: %d\n", skill_array_size);

        // // 先创建一个明显的标题测试显示
        // lv_obj_t * title_label = lv_label_create(lv_chinese_ime->font_panel);
        // char title_text[100];
        // snprintf(title_text, sizeof(title_text), "候选词(%s):", lv_chinese_ime->input_char);
        // lv_label_set_text(title_label, title_text);
        // // lv_obj_set_style_text_color(title_label, lv_color_hex(0x000000), 0);
        // // lv_obj_set_style_bg_color(title_label, lv_color_hex(0x00FFFF), 0);
        // lv_obj_set_style_bg_opa(title_label, LV_OPA_COVER, 0);

        // 显示候选词 - 简化显示，确保可见
        for(int i = 0; i < skill_array_size && i < 20; i++) {
            cJSON * cjson_skill_item = cJSON_GetArrayItem(cjson_skill, i);
            if(cjson_skill_item && cJSON_IsString(cjson_skill_item)) {
                // printf("%s\n",cjson_skill_item->valuestring);

                // 直接创建标签，不使用按钮
                lv_obj_t * label = lv_label_create(lv_chinese_ime->font_panel);
                char candidate_text[50];
                snprintf(candidate_text, sizeof(candidate_text), "%s", cjson_skill_item->valuestring);
                lv_label_set_text(label, candidate_text);

                // 设置非常明显的样式
                // lv_obj_set_style_text_color(label, lv_color_hex(0x000000), 0);
                lv_obj_set_style_bg_color(label, lv_color_hex(0xF6F6F6), 0);
                lv_obj_set_style_bg_opa(label, LV_OPA_COVER, 0);
                // lv_obj_set_style_border_color(label, lv_color_hex(0xFF0000), 0);
                // lv_obj_set_style_border_width(label, 2, 0);
                lv_obj_set_style_pad_all(label, 0, 0);

                // 添加点击事件
                lv_obj_add_flag(label, LV_OBJ_FLAG_CLICKABLE);
                lv_obj_add_event_cb(label, select_font_event_cb, LV_EVENT_CLICKED, kb);
            }
        }
    }

    cJSON_Delete(cjson_parse_result);

    // 强制刷新
    lv_obj_invalidate(lv_chinese_ime->font_panel);
    lv_refr_now(NULL);
    // printf("解析完成，强制刷新显示\n");
}

/**
 * lv_chinese_ime constructor
 * @param obj pointer to a keyboard
 */
static void lv_chinese_ime_constructor(lv_obj_t * obj)
{
    static lv_style_t panel_style; // 摆放文字展示的面板样式

    /* 申请内存 */
    lv_chinese_ime = (lv_chinese_ime_t *)lv_mem_alloc(sizeof(lv_chinese_ime_t));

    /* 摆放文字展示的面板样式 */
    lv_style_init(&panel_style);
    lv_style_set_bg_opa(&panel_style, 255);
    lv_style_set_border_opa(&panel_style, 0);
    lv_style_set_radius(&panel_style, 0);
    lv_style_set_pad_all(&panel_style, 0);

    lv_chinese_ime->dict     = zh_cn_pinyin_dict;
    lv_chinese_ime->ta_count = 0;
    memset(lv_chinese_ime->input_char, 0, sizeof(lv_chinese_ime->input_char));

    // lv_chinese_ime->font_panel = lv_obj_create(obj);
    lv_chinese_ime->font_panel = lv_obj_create(lv_scr_act());
    // lv_obj_clear_flag(lv_chinese_ime->font_panel, LV_OBJ_FLAG_SCROLLABLE);
    lv_obj_add_flag(lv_chinese_ime->font_panel, LV_OBJ_FLAG_HIDDEN);
    lv_obj_set_size(lv_chinese_ime->font_panel, LV_PCT(80), LV_PCT(10));
    lv_obj_set_style_bg_color(lv_chinese_ime->font_panel, lv_color_hex(0xF6F6F6), 0);
    lv_obj_set_flex_flow(lv_chinese_ime->font_panel, LV_FLEX_FLOW_ROW);
    lv_obj_set_flex_align(lv_chinese_ime->font_panel, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER);
    lv_obj_align_to(lv_chinese_ime->font_panel, obj, LV_ALIGN_LEFT_MID, -10, -96);

    lv_obj_add_style(lv_chinese_ime->font_panel, &panel_style, 0);
}
/**
 * lv_chinese_ime destruct
 */
static void lv_chinese_ime_destruct(void)
{
    lv_obj_del(lv_chinese_ime->font_panel);
    lv_mem_free(lv_chinese_ime);
}

#include "../inc/homepage.h"
#include "../inc/user_event.h"
#include "../inc/msg_popup.h"

lv_obj_t * input_keyboard = NULL;

void text_input_event_cb(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * ta        = lv_event_get_target(e);
    lv_obj_t * kb        = (lv_obj_t *)lv_event_get_user_data(e);

    if(code == LV_EVENT_FOCUSED) {
        user_event.chat_kb_open_status = 1;
        // 文本框获得焦点时显示并关联键盘
        lv_keyboard_set_textarea(kb, ta);
        lv_obj_clear_flag(kb, LV_OBJ_FLAG_HIDDEN);
        lv_obj_clear_flag(lv_chinese_ime->font_panel, LV_OBJ_FLAG_HIDDEN);
        memset(lv_chinese_ime->input_char, 0, sizeof(lv_chinese_ime->input_char));
        lv_obj_move_foreground(kb); // 确保键盘在最上层
        lv_obj_set_pos(input_box, 0, LV_PCT(40));
        lv_obj_set_height(chat_window, LV_PCT(30));

    } else if(code == 32) {
        user_event.chat_kb_open_status = 0;
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
        lv_obj_add_flag(lv_chinese_ime->font_panel, LV_OBJ_FLAG_HIDDEN);
        lv_obj_set_pos(input_box, 0, LV_PCT(90));
        lv_obj_set_height(chat_window, LV_PCT(80));
    } else if(code == LV_EVENT_READY) {
        // 确认键被点击时的处理逻辑
        lv_obj_t * ta = lv_keyboard_get_textarea(kb); // 获取当前关联的文本框

        if(ta != NULL) {
            const char * text = lv_textarea_get_text(ta);
            if(strlen(text) == 0) {
                show_msg_box("输入内容不能为空", MSG_TEXT_COLOR_BLACK, MSG_LONG_SHORT);
                return;
            }
            selfChatBubble(chat_window, text); // 显示自己的聊天气泡
            char target_id[32] = "wyf";
            send_private_chat(text, target_id);
            lv_textarea_set_text(ta, ""); // 清空文本框内容
        }
    }
}

#endif /*LV_CHINESE_IME*/